package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/api/dto"
	"github.com/vueadmin/app/api/service"
	"github.com/vueadmin/pkg/cache"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/common/request"
	"github.com/vueadmin/utils/common/result"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
	"time"
)

var Link = new(link)

type link struct{}

/**
 * @description(数据列表)
 * @buildcode(true)
 */
func (link) GetPageList(c *gin.Context) {
	req := dto.LinkPageReq{
		PageReq: request.PageReq{Page: 1, Limit: 20},
	}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	key := fmt.Sprintf("link:list:%s", utils.Md5(conv.ObjectToString(req)))
	if cache.New().Get(key) != "" {
		response.Success(c, "返回成功", conv.StringToObject(cache.New().Get(key)))
		return
	}
	list, count, err := service.LinkService.GetPageList(&req)
	if err != nil {
		response.Err(c, err)
		return
	}
	cache.New().Set(key, conv.ObjectToString(map[string]interface{}{"data": list, "total": count}), 600*time.Second)

	response.Success(c, "返回成功", result.M{
		"data":  list,
		"total": count,
	})
}

/**
 * @description(添加)
 * @buildcode(true)
 */
func (link) Add(c *gin.Context) {
	req := dto.LinkAddReq{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	ret, err := service.LinkService.Add(&req)
	if err != nil {
		response.Err(c, err)
		return
	}
	response.Success(c, "返回成功", ret)
}

/**
 * @description(修改)
 * @buildcode(true)
 */
func (link) Update(c *gin.Context) {
	req := dto.LinkUpdateReq{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	err := service.LinkService.Update(&req)
	if err != nil {
		response.Err(c, err)
		return
	}
	response.Success(c, "修改成功", nil)
}

/**
 * @description(删除)
 * @buildcode(true)
 */
func (link) Delete(c *gin.Context) {
	req := dto.LinkDeleteReq{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	err := service.LinkService.Delete(&req)
	if err != nil {
		response.Err(c, err)
		return
	}
	response.Success(c, "删除成功", nil)
}

/**
 * @description(查看详情)
 * @buildcode(true)
 */
func (link) Detail(c *gin.Context) {
	req := dto.LinkDetailReq{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	key := fmt.Sprintf("link:%d", req.LinkId)
	if cache.New().Get(key) != "" {
		response.Success(c, "返回成功", conv.StringToObject(cache.New().Get(key)))
		return
	}
	info, err := service.LinkService.Detail(&req)
	if err != nil {
		response.Err(c, err)
		return
	}
	cache.New().Set(key, conv.ObjectToString(info), 600*time.Second)
	response.Success(c, "返回成功", info)
}
